import esbuild from "esbuild";
import ReadStream from "../utils/ReadStream.js";
import RewriteImportPath from "../utils/RewriteImportPath.js";
function ReadPathPlugin({ app, root }) {
  app.use(async (ctx, next) => {
    await next();
    // 判断后缀是否为ts或者js
    // ctx.response.is,判断相应对象是否存在和js相关的MIME类型
    if (ctx.response.is("ts") || ctx.response.is("js")) {
      const content = await ReadStream(ctx.body);
      const { code } = esbuild.transformSync(content, {
        loader: "ts",
        target: "es2015",
      });
      ctx.type = "js";
      ctx.body = RewriteImportPath(code);
    }
  });
}

export default ReadPathPlugin;
